package com.sinog.biz.service.business.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.sinog.biz.mapper.havexml.AreaCodeFullMapper;
import com.sinog.biz.mapper.havexml.PrisonerMainMapper;
import com.sinog.biz.mapper.havexml.PrisonerXjxxMapper;
import com.sinog.biz.mapper.havexml.SystemCodeMapper;
import com.sinog.biz.mapper.havexml.XtjcKsywxtMapper;
import com.sinog.biz.service.business.SecXjSbService;
import com.sinog.biz.util.CodeUrlUtils;
import com.sinog.biz.util.IdGen;
import com.sinog.core.domain.InterProvincialBusiness;
import com.sinog.core.domain.PrisonerXjxx;
import com.sinog.core.model.UserDTO;
import com.sinog.core.util.JsonUtil;
import com.sinog.core.utilbean.Constants;
import com.sinog.core.utilbean.Result;
import com.sinog.core.utilbean.ReturnCode;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @desc 衔接上报实现类
 * @author -
 * @date -
 */
@Service
public class SecXjSbServiceImpl implements SecXjSbService {

    @Resource
    private XtjcKsywxtMapper xtjcKsywxtMapper;
    @Resource
    private PrisonerXjxxMapper prisonerXjxxMapper;
    @Resource
    private SystemCodeMapper systemCodeMapper;
    @Resource
    private PrisonerMainMapper prisonerMainMapper;
    @Resource
    private AreaCodeFullMapper areaCodeFullMapper;

    /**
     * 根据罪犯编号获取跨省业务协调省的数据
     * @param priNum 罪犯编号
     * @return String
     */
    @Override
    public String getInterProvincialBusinessInfo(String priNum) {
        InterProvincialBusiness business = xtjcKsywxtMapper.getInterProvincialBusinessByPriNum1(priNum);
        return JsonUtil.toText(business);
    }

    /**
     * 根据罪犯编号获取衔接信息表中的主键id
     * @param priNum 罪犯编号
     * @return String
     */
    @Override
    public String getXjxxIdByPriNum(String priNum) {
        return prisonerXjxxMapper.getXjxxIdByPriNum(priNum);
    }

    /**
     * 保存信息
     * @param data data
     * @param user user
     * @return Result
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result saveXjReport(String data,UserDTO user) {
        //本系统的本地code
        String localCode = CodeUrlUtils.getLocalCode();
        Map<String,Object> paramMap = JsonUtil.toMap(data);
        InterProvincialBusiness business = JsonUtil.toBean(data,InterProvincialBusiness.class);
        PrisonerXjxx prisonerXjxx = new PrisonerXjxx();
        Date date = new Date();
        prisonerXjxx.setCreateUser(user.getAccount());
        prisonerXjxx.setCreateTime(date);
        prisonerXjxx.setUpdateUser(user.getAccount());
        prisonerXjxx.setUpdateTime(date);
        prisonerXjxx.setPriNum(business.getPriNum());
        // 01:监狱   09:监狱局   06:司法厅  02:看守所  05:社矫
        if(Constants.OrgLevel.LEVEL_JY.equals(user.getLevel()) || Constants.OrgLevel.LEVEL_KSS.equals(user.getLevel()) || Constants.OrgLevel.LEVEL_SJZX.equals(user.getLevel())) {
            prisonerXjxx.setSecondState(Constants.NumberStr.NUM_STR_ONE);
        } else if(Constants.OrgLevel.LEVEL_JYJ.equals(user.getLevel()) || Constants.OrgLevel.LEVEL_SSJ.equals(user.getLevel()) || Constants.OrgLevel.LEVEL_JGZONGD.equals(user.getLevel())) {
            prisonerXjxx.setSecondState(Constants.NumberStr.NUM_STR_TWO);
        } else if(Constants.OrgLevel.LEVEL_SFT.equals(user.getLevel())) {
            // 1:本省协调 2:跨省业务协调
            if(Constants.NumberStr.NUM_STR_ONE.equals(paramMap.get(Constants.StrFinalValue.FLAG))) {
                if(Constants.NumberStr.NUM_STR_SIX.equals(paramMap.get(Constants.StrFinalValue.SECONDSTATE)
                                                                  .toString())) {
                    prisonerXjxx.setSecondState(Constants.NumberStr.NUM_STR_SEVEN);
                } else if(Constants.NumberStr.NUM_STR_TWO.equals(paramMap.get(Constants.StrFinalValue.SECONDSTATE)
                                                                         .toString())) {
                    prisonerXjxx.setSecondState(Constants.NumberStr.NUM_STR_THREE);
                }
                //司法厅处理衔接失败人员
                //todo:司法厅处理二次衔接分配司法所时，户籍地址需变更-main表和ab表都需要注意
                business.setState("");
                prisonerXjxx.setSecondProvince(paramMap.get("nativepro").toString());
                prisonerXjxx.setSecondCity(paramMap.get("nativecity").toString());
                prisonerXjxx.setSecondCounty(paramMap.get("nativecou").toString());
                prisonerXjxx.setSecondStreet(paramMap.get("nativevill").toString());
                business.setSftlxr("");
                business.setSftphone("");
                business.setSfttel("");
                business.setSftyj("");
            } else {
                business.setDssftszsOld(localCode);
                prisonerXjxx.setSecondState(Constants.NumberStr.NUM_STR_FOUR);
                business.setState(Constants.NumberStr.NUM_STR_FU_ONE);
                prisonerXjxx.setSecondProvince("");
                prisonerXjxx.setSecondCity("");
                prisonerXjxx.setSecondCounty("");
                prisonerXjxx.setSecondStreet("");
            }
        }
        if(null == business.getId() || "".equals(business.getId())) {
            business.setId(IdGen.strid());
        }
        UpdateWrapper<PrisonerXjxx> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("pri_num",business.getPriNum());
        boolean b = business.insertOrUpdate();
        InterProvincialBusiness result = xtjcKsywxtMapper.selectById(business.getId());
        Map<String,Object> resutlMap = JsonUtil.toMap(JsonUtil.toText(result));
        resutlMap.put("flag",paramMap.get("flag"));
        if(Constants.NumberStr.NUM_STR_ONE.equals(paramMap.get(Constants.StrFinalValue.FLAG)) && Constants.OrgLevel.LEVEL_SFT.equals(user.getLevel())) {
            resutlMap.put("nativepro",paramMap.get("nativepro").toString());
            resutlMap.put("nativecity",paramMap.get("nativecity").toString());
            resutlMap.put("nativecou",paramMap.get("nativecou").toString());
            resutlMap.put("nativevill",paramMap.get("nativevill").toString());
            String nativepro = paramMap.get("nativepro").toString();
            String nativecity = paramMap.get("nativecity").toString();
            String nativecou = paramMap.get("nativecou").toString();
            String nativevill = paramMap.get("nativevill").toString();
            if (StringUtils.isNotBlank(nativepro)){
                Map<String,String> areaNames = areaCodeFullMapper.getAreaNames(nativepro,nativecity,nativecou,nativevill);
                if (areaNames == null){
                    return Result.failure(ReturnCode.SAVE_FAILED);
                }
                resutlMap.put("nativeproName",areaNames.get("shengName"));
                resutlMap.put("nativecityName",areaNames.get("dishiName"));
                resutlMap.put("nativecouName",areaNames.get("quxianName"));
                resutlMap.put("nativevillName",areaNames.get("jiedaoName"));
                if (StringUtils.isBlank(nativecity)){
                    resutlMap.put("nativecityName","");
                }
                if (StringUtils.isBlank(nativecou)){
                    resutlMap.put("nativecouName","");
                }
                if (StringUtils.isBlank(nativevill)){
                    resutlMap.put("nativevillName","");
                }
            } else {
                resutlMap.put("nativeproName","");
                resutlMap.put("nativecityName","");
                resutlMap.put("nativecouName","");
                resutlMap.put("nativevillName","");
            }
        }
        int row = prisonerXjxxMapper.update(prisonerXjxx,updateWrapper);
        if(b && (0 < row)) {
            return Result.success(resutlMap);
        }
        return Result.failure(ReturnCode.FAILURE);
    }

    /**
     * 查看上报页面信息
     * @param priNum 罪犯编号
     * @return String
     */
    @Override
    public String getReportInfo(String priNum) {
        Map<String,Object> resultMap = xtjcKsywxtMapper.getReportInfo(priNum);
        if(null != resultMap) {
            if(Constants.NumberStr.NUM_STR_THREE.equals(resultMap.get(Constants.StrFinalValue.SECONDSTATE))) {
                Map<String,String> map = new HashMap<>(16);
                map.put("codeType",Constants.CodeType.CODE_ZHRMGHG_XZQH_DM);
                map.put("codeId",(String)resultMap.get("secondprovince"));
                Object secondprovince = resultMap.get("secondprovince");
                resultMap.put("secondprovince",null == secondprovince ? "" : (null == systemCodeMapper.getCodeByMap(map) ? "" :systemCodeMapper.getCodeByMap(map).getCodeName()));
                map.put("codeId",(String)resultMap.get("secondcity"));
                Object secondcity = resultMap.get("secondcity");
                resultMap.put("secondcity",null == secondcity ? "" : (null == systemCodeMapper.getCodeByMap(map) ? "" :systemCodeMapper.getCodeByMap(map).getCodeName()));
                map.put("codeId",(String)resultMap.get("secondcounty"));
                Object secondcounty = resultMap.get("secondcounty");
                resultMap.put("secondcounty",null == secondcounty ? "" : (null == systemCodeMapper.getCodeByMap(map) ? "" :systemCodeMapper.getCodeByMap(map).getCodeName()));
                Object secondstreet = resultMap.get("secondstreet");
                resultMap.put("secondstreet",null == secondstreet ? "" : systemCodeMapper.getNameByCode(resultMap.get("secondstreet").toString()));
            } else {
                resultMap.put("secondprovince","");
                resultMap.put("secondcity","");
                resultMap.put("secondcounty","");
                resultMap.put("secondstreet","");
            }
        }
        return JsonUtil.toText(resultMap);
    }

    /**
     * 重新发起衔接页面信息
     * @param priNum 罪犯编号
     * @return String
     */
    @Override
    public String getAgainXjPageInfo(String priNum) {
        Map<String,Object> resultMap = prisonerMainMapper.getAgainXjPageInfo(priNum);
        Map<String,String> map = new HashMap<>(16);
        map.put("codeType",Constants.CodeType.CODE_ZHRMGHG_XZQH_DM);
        map.put("codeId",(String) resultMap.get("secondprovince"));
        Object secondprovince = resultMap.get("secondprovince");
        resultMap.put("secondprovince",null == secondprovince ? "" : (null == systemCodeMapper.getCodeByMap(map) ? "" :systemCodeMapper.getCodeByMap(map).getCodeName()));
        map.put("codeId",(String)resultMap.get("secondcity"));
        Object secondcity = resultMap.get("secondcity");
        resultMap.put("secondcity",null == secondcity ? "" : (null == systemCodeMapper.getCodeByMap(map) ? "" :systemCodeMapper.getCodeByMap(map).getCodeName()));
        map.put("codeId",(String)resultMap.get("secondcounty"));
        Object secondcounty = resultMap.get("secondcounty");
        resultMap.put("secondcounty",null == secondcounty ? "" : (null == systemCodeMapper.getCodeByMap(map) ? "" :systemCodeMapper.getCodeByMap(map).getCodeName()));
        Object secondstreet = resultMap.get("secondstreet");
        resultMap.put("secondstreet",null == secondstreet ? "" : systemCodeMapper.getNameByCode(resultMap.get("secondstreet").toString()));
        return JsonUtil.toText(resultMap);
    }
}